package com.inspire.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.cmbc.nccs.filter.impl.in.BaseDataParseInFilter;
import com.cmbc.nccs.filter.impl.in.impl.BaseImpl;
import com.inspire.springboot.dbutil.DBHelper;
import com.inspire.springboot.dbutil.OracleJdbc;
import com.inspire.springboot.domain.Goods;
import com.inspire.springboot.domain.User;
import com.inspire.springboot.impl.LibVerifyOldCustomerReqVOImpl;
import com.inspire.springboot.mapper.GoodsXmlMapper;
import com.inspire.springboot.mapper.UserMapper;
import com.inspire.springboot.mapper.UserXmlMapper;
import com.inspire.springboot.service.*;
import com.inspire.springboot.service.imp.*;
import com.jettech.dubbo.zjnx.client.DubboClientPro;
import com.tesla.gateway.core.message.GatewayMessage;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
public class MQController {
    // 为了保证使用时，不需要每次都去创建logger 对象，我们声明静态常量
    public static final Logger logger = LoggerFactory.getLogger(MQController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserXmlMapper userXmlMapper;

    @Autowired
    private GoodsXmlMapper goodsXmlMapper;

    @Autowired
    private LibVerifyOldCustomerRespVO libVerifyOldCustomerRespVO;

    @RequestMapping("sendDemo/{id}")
    public String sendDemo(@PathVariable("id") int id){
        logger.info("Hello:"+id);
//        destroy();

        logger.debug("----------------------------paic_buildMerchantDTOList----------------------------");
//        paic_buildMerchantDTOList("aaa");
//        libVerifyOldCustomerRespVO.process(new LibVerifyOldCustomerReqVOImpl());
//        List<User> all = userMapper.findAll();
        List<User> all2 = userXmlMapper.findAll();
//        logger.info("注解方式查询："+all);
        logger.info("Xml方式查询："+all2);

        User byID = userXmlMapper.findByID(1);
        logger.info("id 1:"+byID.toString());

        //java语法验证
        //1.接口实现
        mdHelloService1();
        mdHelloService2();
        mdHelloService3();

        //2.继承关系验证
        mdEmployeeService1();
        mdEmployeeService2();

        BaseDataParseInFilter filter=new BaseImpl();
        String s = filter.fixCommonService(new GatewayMessage(), new JSONObject(), "", "", "");
        logger.info("minshengka-s="+s);

        testFindAll();
        testFindGoodsByID();
        testInsertGoods();
        testUpdateStockByName();
        testFindGoodsByName();
        testDeleteGoodsByName();
        testFindGoodsByIds();
        
        zhejiangnongxinInterCeptor();
        return "sendDemo7:"+userService.helloIUser("aaa");
    }

    public void zhejiangnongxinInterCeptor(){
        Map<String, Object> reqMap=new HashMap<>();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("cluster","");
        jsonObject.put("referenceBean","");
        reqMap.put("connectAttr",jsonObject.toString());
        reqMap.put("registryBean","dap");
        reqMap.put("Accept","*/*");

        JSONObject jsonObject2=new JSONObject();

        JSONObject ctrlDataJson=new JSONObject();
        ctrlDataJson.put("appPushId","");
        ctrlDataJson.put("transDesc","");
        jsonObject2.put("ctrlData",ctrlDataJson);

        JSONObject bodyJson=new JSONObject();
        bodyJson.put("prodcd","DJ000001");
        bodyJson.put("teststars","user");
        jsonObject2.put("body",bodyJson);
        reqMap.put("data",jsonObject2);
        new DubboClientPro().send(reqMap);
    }

    public void testFindAll(){
        List<Goods> all = goodsXmlMapper.findAll();
        System.out.println(all);
    }

    public void testFindGoodsByID(){
        Goods goodsByID = goodsXmlMapper.findGoodsByID(1);
        System.out.println(goodsByID);
    }

    public void testInsertGoods(){
        Goods goods=new Goods();
        goods.setGoodsName("百香果");
        goods.setStock(300);
        goods.setGoodsDescribe("临潼的百香果");
        int i = goodsXmlMapper.insertGoods(goods);
        System.out.println(i);
    }

    public void testDeleteGoodsByName(){
        int goods = goodsXmlMapper.deleteGoodsByName("石榴");
        System.out.println(goods);
    }

    public void testUpdateStockByName(){
        Goods goods=new Goods();
        goods.setGoodsName("香蕉");
        goods.setStock(310);
        int i = goodsXmlMapper.updateStockByName(goods);
        System.out.println(i);
    }

    /*
    模糊查询
     */
    public void testFindGoodsByName(){
        List<Goods> 香 = goodsXmlMapper.findGoodsByName("香");
        System.out.println(香);
    }

    public void testFindGoodsByIds(){
        List<Integer> ids=new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        List<Goods> goodsByIds = goodsXmlMapper.findGoodsByIds(ids);
        System.out.println(goodsByIds);
    }

    public static void mdHelloService1(){
        HelloService helloService=new HelloServiceImpl();
        callHelloService(helloService);
    }
    public static void mdHelloService2(){
        HelloService helloService=new HelloServiceTwoImpl();
        callHelloService(helloService);
    }
    public static void mdHelloService3(){
        HelloService2 helloService2=new HelloServiceImpl();
        helloService2.hello2();
    }

    public static void mdEmployeeService1(){
        EmployeeService employeeService=new EmployeeServiceImpl();
        callEmployeeService(employeeService);
    }
    public static void mdEmployeeService2(){
        EmployeeService employeeService=new EmployeeServiceTwoImpl();
        callEmployeeService(employeeService);
    }

    public static void callHelloService(HelloService helloService){
        logger.info(helloService.hello());
    }

    public static void callEmployeeService(EmployeeService employeeService){
        logger.info(employeeService.getRealName("abc"));
    }

    @PostMapping("/sendDemo02/{id}")
    @ResponseBody
    public String sendDemo02(@PathVariable("id") int id){
        logger.info("id:"+id);
        logger.debug("----------------------------paic_buildMerchantDTOList----------------------------");
        paic_buildMerchantDTOList("aaa");
//        libVerifyOldCustomerRespVO.process(new LibVerifyOldCustomerReqVOImpl());
        deleteByNameTest();
        return "sendDemo02-success!";
    }

    @PutMapping("/sendDemo03/{id}")
    @ResponseBody
    public String sendDemo03(@PathVariable("id") int id){
        logger.info("id:"+id);
        print(1);
        testMulti_Conditional_Line_Feed_If();

        System.out.println("---------------------test----------------------");
//        insertTest();
        return "sendDemo02-success!";
    }

    @RequestMapping("sendDemo05/{id}")
    public String sendDemo05(@PathVariable("id") int id){
        logger.info("Hello:"+id);
        Map<String,String> map=new HashMap<>();
        logger.info("MinSheng_Map:"+getMap_MinSheng(map));
        return "sendDemo05";
    }
    @RequestMapping("sendDemo06/{id}")
    public String sendDemo06(@PathVariable("id") int id){
        PerforTesting perforTesting;
        String testName="sendDemo06";
        long start = System.currentTimeMillis();

        if(id==1){
            perforTesting=new PerforTestingMethodImpl();
            perforTesting.test();
            testName="MethodMode";
        }else if(id==2){
            perforTesting=new PerforTestingArrayImpl();
            perforTesting.test();
            testName="ArrayMode";
        }else if(id==4){
            perforTesting=new PerforTestingArrayImpl();
            perforTesting.indexDef();
            testName="indexDef";
        } else if(id==5){
            perforTesting=new PerforTestingArrayImpl();
            perforTesting.test2();
            testName="Biz";
        } else if(id==6){
            perforTesting=new PerforTestingArrayImpl();
            perforTesting.indexDef2();
        }
        long cost=System.currentTimeMillis()-start;
        return testName+":"+cost+"ms";
    }

    @RequestMapping("sendDemo07/{id}")
    public String sendDemo07(@PathVariable("id") int id){
        paic_buildMerchantDTOList("aaa");
        return "lambdaTest";
    }

    @PostMapping("sendDemo08")
    public String sendDemo08(@RequestBody Goods goods){
        System.out.println("1."+goods.toString());
        return "sendDemo08";
    }

    @GetMapping("query1")
    public String query1(){
        MySqlService mySqlService = new MySqlService();
        mySqlService.query();
        return "query1!";
    }

    @GetMapping("query2")
    public String query2(){
        MySqlService mySqlService = new MySqlService();
        mySqlService.selectList();
        return "query2!";
    }

    public void insertTest() {
        Connection conn = null;
        PreparedStatement  ps = null;

        try {
            // 1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 2.得到连接
            conn = new DBHelper().getConnection(new OracleJdbc());
            String sql = "insert into TEST_1 VALUES (?,?,?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,"lisi");//name
            ps.setString(2,"123456");//password
            ps.setInt(3,22);//age
            ps.setDate(4,strToDate("2000-10-18"));//birthday
            ps.setString(5,"xian");//address VarcharBinder type:9
            ps.setFloat(6,10001.56f);//salary
            ps.setLong(7, UUID.randomUUID().getMostSignificantBits());//idCard
            ps.setTimestamp(8,changeDate("2022-10-10"));//salaryData TimestampBinder type:180
            ps.setDouble(9,8001);//annualBonus

            int i = ps.executeUpdate();
            System.out.println(i);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static Timestamp changeDate(String date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp ts = null;
        try {
            Date parse = sdf.parse(date);
            ts = new Timestamp(parse.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ts;
    }

    public java.sql.Date strToDate(String strDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date d = null;
        try {
            d = format.parse(strDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        java.sql.Date date = new java.sql.Date(d.getTime());
        return date;
    }

    public void deleteByNameTest() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = new DBHelper().getConnection(new OracleJdbc());
            String sql = "delete from TEST_1 where NAME = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "zhangsan");
            int i = ps.executeUpdate();
            System.out.println(i);

//            String sql = "DELETE from person where id=2";
//            ps = conn.prepareStatement(sql);
//            boolean execute = ps.execute();
//            System.out.println(execute);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /*
    TODO:https://blog.csdn.net/weixin_48860638/article/details/121451280
    TODO:https://blog.csdn.net/demo_yo/article/details/123608034
     */
    @GetMapping("/sendDemo04")
    @ResponseBody
    public List<String> sendDemo04(@RequestParam("strs") List<String> strs){
        logger.info(""+strs);
        finallyWithBreak();
        return strs;
    }

    public static void print(int a) {
        if (a > 0) {
            logger.debug("^v^---^v^ :a>0");
        } else {
            logger.debug("^v^---^v^ :a<0");
        }
    }
    private String finallyWithBreak() {
        List<Integer> list;
        int num = 0;
        logger.debug("=========== begin ============");
        try {
            //list格式
            list = new ArrayList<>();
            list.add(0);
            list.add(1);
            list.add(2);
            int a = 2 / 1;
            if (a == 2) {

                logger.debug("======== error =========");
            }
            logger.debug("========= aaa1 =========");
        } catch (ArithmeticException e) {
            logger.debug("======== catche ==========");
            e.printStackTrace();
        } finally {
            while (num < 5) {
                num++;
                logger.debug("num = " + num);
                if (num == 3) {
                    break;
                }
            }
            logger.debug("============= finally =============");
        }

        return "finallyTest";
    }
    private static void testMulti_Conditional_Line_Feed_If() {
        //A||(B&&C)||D&&E
        int a = 0;
        String b = "bbb";
        int c = 1;
        int d = 2;
        String e = "eee";
        if (a == 0 ||
                ("bbb".equals(b) && c == 1) ||
                d == 2 &&
                        "eee" == e) {
            if((a+1)==1){
                throw new RuntimeException();
            }
            System.out.println("--------------------test2---------------------");
            logger.debug("Line_Feed_If true ******");
        } else {
            logger.debug("Line_Feed_If false ******");
        }

    }

    /*
    ifPresent详解 https://www.csdn.net/tags/Ntjacg1sMjM2MzEtYmxvZwO0O0OO0O0O.html
    函数逻辑说明：当offlineMerchantInfoResDTO不为空时，将list中的元素add进offlineMerchantDTOList
     */
    private List<String> paic_buildMerchantDTOList(String offlineMerchantInfoResDTO) {
        List<String> offlineMerchantDTOList = new CopyOnWriteArrayList<>();
        List<String> list = Arrays.asList("A123", "B123", "C123", "A321");
        Optional.ofNullable(offlineMerchantInfoResDTO)
                .ifPresent(list1 -> list.stream().parallel().forEach(offlineMerchantDTO -> {
                            try {
                                findMerchantLocation(offlineMerchantDTO);
                                offlineMerchantDTOList.add(offlineMerchantDTO);
                            } catch (Exception ex) {
                                //注释......
                                logger.error("findMerchantLocation error:{}", offlineMerchantDTO);
                            }
                        })
                );
        return offlineMerchantDTOList;

    }

    private void findMerchantLocation(String offlineMerchantDTO) {
        logger.info("offlineMerchantDTO:" + offlineMerchantDTO);
    }

    public void destroy() {
        logger.info("--- GC ---");
        System.gc();
    }

    public Map<String,String> getMap_MinSheng(Map<String,String> map){
        if(StringUtils.isEmpty(map)){
            logger.info("map is empty!");
            return null;
        }else{
            logger.info("map is not empty!");
            return map;
        }

    }
}

